package cn.tedu.egcar1.controller;

import cn.tedu.egcar1.base.response.JsonResult;
import cn.tedu.egcar1.base.response.StatusCode;
import cn.tedu.egcar1.mapper.UserMapper;
import cn.tedu.egcar1.pojo.dto.UserLoginParam;
import cn.tedu.egcar1.pojo.dto.UserRegParam;
import cn.tedu.egcar1.pojo.entity.User;
import cn.tedu.egcar1.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@Api(tags="1.用户管理系统")
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /*
    用户注册系统
     */
    @ApiOperation(value = "用户注册")
    @ApiOperationSupport(order=10)
    @PostMapping("reg")
    public JsonResult userReg(@RequestBody UserRegParam userRegParam){
        log.debug("userRegParam:"+userRegParam);
        int a = userMapper.selectUser(userRegParam.getUsername());
        if (a>0){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();




    }

    @ApiOperation(value = "用户登录")
    @ApiOperationSupport(order=20)
    @PostMapping("login")
    public JsonResult userLogin(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session){
        log.debug("userLoginParam:"+userLoginParam);
        String username = userLoginParam.getUsername();
        String password = userLoginParam.getPassword();
        UserVO userVO = userMapper.selectUserByUsernameAndPassword(username,password);
        session.setAttribute("user",userVO);
        if (userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        return JsonResult.ok();
    }

    @ApiOperation(value="获取当前用户功能")
    @ApiOperationSupport(order=30)
    @GetMapping("currentUser")
    public JsonResult getCurrentUser(@ApiIgnore HttpSession session){
        UserVO userVO =(UserVO) session.getAttribute("user");
        if (userVO==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        return JsonResult.ok(userVO);
    }

    @ApiOperation(value="退出登录")
    @ApiOperationSupport(order=40)
    @GetMapping("logout")
    public void logoutUser(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }
}
